import { useUserStore } from '@/store'

/**
 * 权限控制指令
 * 使用方法：v-hasPermi="['system:user:add']" 或 v-hasPermi="'system:user:add'"
 */
export default {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    const permissions = userStore.permissions || []
    const all_permission = "*:*:*"
    
    // 如果用户有超级权限，直接显示
    if (permissions.includes(all_permission)) {
      return
    }
    
    // 检查权限
    let hasPermission = false
    if (value && value.length > 0) {
      // 支持字符串和数组格式
      const permissionList = Array.isArray(value) ? value : [value]
      
      hasPermission = permissionList.some(permission => {
        return permissions.includes(permission)
      })
    }
    
    // 没有权限则隐藏元素
    if (!hasPermission) {
      el.style.display = 'none'
    }
  },
  
  updated(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    const permissions = userStore.permissions || []
    const all_permission = "*:*:*"
    
    // 如果用户有超级权限，直接显示
    if (permissions.includes(all_permission)) {
      el.style.display = ''
      return
    }
    
    // 检查权限
    let hasPermission = false
    if (value && value.length > 0) {
      // 支持字符串和数组格式
      const permissionList = Array.isArray(value) ? value : [value]
      
      hasPermission = permissionList.some(permission => {
        return permissions.includes(permission)
      })
    }
    
    // 根据权限显示或隐藏元素
    if (hasPermission) {
      el.style.display = ''
    } else {
      el.style.display = 'none'
    }
  }
}
